<template>
  <div class="page_space btn_space">
    <p class="title_1">被采样主体信息</p>
    <input-card>
      <inputItem title="经营主体" :content="params.intercourseEnterpriseName" />
      <inputItem title="主体类型" :content="params.subjectTypeText" />
      <inputItem title="所属市场" :content="params.managementEntName" />
    </input-card>

    <p class="title_1">基本信息</p>
    <input-card>
      <inputItem
        title="快检类型"
        tip="请选择快检类型"
        type="select"
        :content="params.inspectType"
        @select="toSelect(0)"
      />
      <inputItem
        title="采样人员"
        tip="请选择采样人员"
        type="select"
        :content="params.handlerName"
        @select="goto('/select-sampler')"
      />
      <inputItem
        title="采样日期"
        tip="请选择采样日期"
        type="select"
        :content="params.billDate"
        @select="toSelect(1)"
      />
    </input-card>

    <p class="title_1">样品信息</p>
    <input-card>
      <inputItem
        title="样品自编号（选填）"
        tip="请输入样品自编号"
        type="input"
        :content="params.details[0].businessVarietyCode"
        @input="(e) => (params.details[0].businessVarietyCode = e)"
        @select="toSelect(0)"
      />
      <inputItem
        title="样品名称"
        tip="请选择样品"
        type="select"
        :content="params.details[0].businessVarietyName"
        @select="goto('/select-sample')"
      />
      <input-item-number
        v-model="params.details[0].num"
        :unit="params.details[0].packUnitName"
        title="采样数量"
        tip="请输入采样数量"
        :unitList="['千克', '克']"
        @changeUnit="(e) => (params.details[0].packUnitName = e)"
      />
    </input-card>

    <p class="title_1">样品供货信息(选填)</p>
    <input-card v-if="params.details[0].intercourseEnterpriseName === ''">
      <div class="tip_add">
        <p>暂无供货信息</p>
        <button @click="addSupplyInfo">
          <span><span class="plus">+</span>添加供货信息</span>
        </button>
      </div>
    </input-card>
    <cardWrap v-else :title="params.details[0].intercourseEnterpriseName">
      <cardItem title="进货日期">{{ params.details[0].produceDate }}</cardItem>
      <cardItem title="进货数量"
        >{{ params.details[0].secondNum }}
        <span v-if="params.details[0].secondNum">千克</span></cardItem
      >
      <cardItem title="产地">{{
        params.details[0].originPlaceInfoAreaName
      }}</cardItem>
      <template #footer>
        <cardBtn
          leftText="删除"
          rightText="编辑"
          leftDanger
          @leftClick="deleteSampleInfo"
          @rightClick="editSampleInfo(params.details[0])"
        />
      </template>
    </cardWrap>

    <p class="title_1">备注与附件</p>
    <input-card class="attachment">
      <!-- <inputItem
        title="附件（选填）"
        tip="支持上传.png,.jpg文件,单个文件大小10M,最多上传5张"
        type="upload"
        @upload="(e) => (params.businessFileDTO = e)"
      /> -->
      <input-item-upload
        title="附件（选填）"
        tip="支持上传.png,.jpg文件,单个文件大小10M,最多上传5张"
      >
        <file-upload
          v-model="params.businessFileDTO"
          :maxLen="5"
          deletable
          @change="changeFile($event)"
        />
      </input-item-upload>
      <input-item-textarea
        v-model="params.description"
        title="备注信息（选填）"
        tip="请输入备注"
        :textRows="4"
      />
    </input-card>

    <div class="btn_wrap">
      <button class="btn middle default" @click="saveDraft">存草稿</button>
      <button class="btn middle" @click="submit">提交</button>
    </div>

    <van-popup v-model="show" position="bottom" :round="true">
      <!-- 快检类型 -->
      <template v-if="active === 0">
        <van-picker
          ref="pickerForInspect"
          title="选择快检类型"
          show-toolbar
          :columns="['政府快检', '自检']"
          visible-item-count="3"
        />
        <div class="btn_box">
          <button class="btn large" @click="confirmInspectType">确定</button>
        </div>
      </template>

      <!-- 选择日期 -->
      <template v-if="active === 1">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          title="选择年月日"
          visible-item-count="3"
        />
        <div class="btn_box">
          <button class="btn large" @click="submitTime">确定</button>
        </div>
      </template>
    </van-popup>
  </div>
</template>

<script>
import inputCard from '@/components/input-card/card'
import inputItem from '@/components/input-card/item'
import cardWrap from '@/components/base-card/wrap'
import cardItem from '@/components/base-card/item'
import cardBtn from '@/components/base-card/btn'
import inputItemTextarea from '@/components/input-card/item-textarea'
import inputItemNumber from '@/components/input-card/item-number'
import fileUpload from '@/components/file-upload'
import inputItemUpload from '@/components/input-card/item-upload'
import { getDraftOfEdit } from '@/api/bill'
import { postSampling } from '@/api/subject'
import { ParseDate, delKeepaliveCache } from '@/utils'
import { store, mutations } from '@/observable'

export default {
  name: 'editDraft',
  components: {
    inputCard,
    inputItem,
    cardWrap,
    cardItem,
    cardBtn,
    inputItemTextarea,
    inputItemUpload,
    fileUpload,
    inputItemNumber
  },
  data() {
    return {
      show: false,
      active: 0,
      currentDate: new Date(),
      varietyId: '', // 新增进货需要用到 样品id

      params: {
        id: '',
        intercourseEnterpriseId: '', // 经营主体id
        intercourseEnterpriseName: '', // 经营主体
        subjectTypeText: '', // 主体类型 中文
        managementEntName: '', // 所属市场
        subjectType: '', // TemporaryOperatingArea 市场内临时经营者； FixedPlace 市场内固定档口； OtherSellersOfEdibleAgricultural 市场外固定经营者
        // uscId: '440508600458992',
        // legalPerson: '吴举钿',
        placeId: '1', // 档口id
        description: '', // 备注
        inspectType: '', // 快检类型 中文
        uploadBizType: '', // 快检类型 政府快检：governmentCheck ， 自检：ownCheck
        handlerName: '', // 采样人员名称
        handlerId: '', // 采样人员id
        billDate: '', // 采样日期
        type: 'SampleBill',
        actionCode: 'ACTION_DATA_CYTZ_CG_TO_CG',
        state: 'ToBeChecked',
        businessFileDTO: [], // 上传文件
        businessFileDTOJson: '',
        billNo: '',
        details: [
          {
            id: '',
            // 样品字段
            businessVarietyCode: '', // 样品自编号
            businessVarietyName: '', // 样品名称
            businessVarietyId: '', // 样品id
            // 供货字段
            num: '', // 数量
            packUnitName: '',
            producer: '', // 进口 TRUE ; 国产 FALSE
            field10: '',
            relationBillDetailId: '',
            intercourseEnterpriseName: '',
            secondNum: '',
            originPlaceInfoName: '',
            originPlaceInfoAreaName: '',
            produceDate: '',
            billNo: ''
          }
        ], // 样品信息
        detailsJson: ''
      }
    }
  },
  created() {
    this.params.id = this.$route.query.id
    this.getDraftInfo(this.params.id)
  },
  beforeRouteLeave(to, from, next) {
    // 返回 清除缓存
    if (to.name === 'samplingLedger' || to.name === 'samplingDetails') {
      mutations.setSampler({})
      mutations.setSample({})
      mutations.setSupplyInfo({})
      delKeepaliveCache(this)
      console.log('销毁:', to.name)
    }
    next()
  },
  activated() {
    console.log('activated')
    // 获取-供货信息
    if (JSON.stringify(store.supplyInfo) !== '{}') {
      let info = store.supplyInfo
      console.log('供货信息', info)
      for (let item in info) {
        this.params.details[0][item] = info[item] || ''
      }
      this.params.details[0].originPlaceInfoAreaName = info.areaName || ''
    }
    // 获取-样品
    if (JSON.stringify(store.sampleInfo) !== '{}') {
      let info = store.sampleInfo
      this.params.details[0].businessVarietyName =
        info.businessVarietyName || ''
      this.params.details[0].businessVarietyId = info.businessVarietyId || ''
      this.varietyId = info.varietyId || ''
    }
    // 获取-采样人员
    if (JSON.stringify(store.samplerInfo) !== '{}') {
      let info = store.samplerInfo
      this.params.handlerName = info.handlerName || ''
      this.params.handlerId = info.handlerId || ''
    }
  },
  methods: {
    // 添加供货信息
    addSupplyInfo() {
      // if (this.varietyId === '') {
      //   this.$toast('请先选择样品名称！')
      //   return false
      // }
      this.$router.push({
        name: 'addSupplyInfo',
        query: {
          intercourseEnterpriseId: this.params.intercourseEnterpriseId,
          varietyId: this.varietyId
        }
      })
    },
    // 上传附件
    changeFile(e) {
      console.log(e)
      this.params.businessFileDTO = e
    },
    // 获取草稿信息
    async getDraftInfo(id) {
      const { code, data } = await getDraftOfEdit(id)
      if (code === '0') {
        // console.log('data:', data)
        // 被采样主体信息
        this.params.intercourseEnterpriseId = data.intercourseEnterpriseId
        this.params.intercourseEnterpriseName = data.intercourseEnterpriseName
        this.params.subjectType = data.intercourseEnterpriseDTO.subjectType
        this.params.subjectTypeText =
          data.intercourseEnterpriseDTO.subjectTypeText
        this.params.managementEntName = data.managementEntName
        // 基本信息
        this.params.inspectType = data.uploadBizTypeText
        this.params.uploadBizType = data.uploadBizType
        this.params.handlerName = data.handlerName
        this.params.handlerId = data.handlerId
        this.params.billDate = data.billDate
        this.params.billNo = data.billNo
        // 样品信息
        this.varietyId = data.detailInfoDTOS[0].varietyId // 样品id
        this.params.details[0].id = data.detailInfoDTOS[0].id
        this.params.details[0].businessVarietyCode =
          data.detailInfoDTOS[0].businessVarietyCode
        this.params.details[0].businessVarietyName =
          data.detailInfoDTOS[0].businessVarietyName
        this.params.details[0].businessVarietyId =
          data.detailInfoDTOS[0].businessVarietyId
        this.params.details[0].num = data.detailInfoDTOS[0].num
        this.params.details[0].packUnitName =
          data.detailInfoDTOS[0].packUnitName
        this.params.details[0].field10 = data.detailInfoDTOS[0].field10
        // 样品供货信息
        this.params.details[0].intercourseEnterpriseName =
          data.detailInfoDTOS[0].intercourseEnterpriseName
        this.params.details[0].produceDate = data.detailInfoDTOS[0].produceDate
        this.params.details[0].secondNum = data.detailInfoDTOS[0].secondNum
        this.params.details[0].originPlaceInfoAreaName =
          data.detailInfoDTOS[0].originPlaceInfoAreaName
        this.params.details[0].originPlaceInfoName =
          data.detailInfoDTOS[0].originPlaceInfoName
        this.params.details[0].producer = data.detailInfoDTOS[0].producer
        this.params.details[0].billNo = data.detailInfoDTOS[0].billNo
        this.params.details[0].relationBillDetailId = data.detailInfoDTOS[0].relationBillDetailId
        // 备注与附件
        this.params.description = data.description
        data.businessFileDTOList.forEach((file) => {
          this.params.businessFileDTO.push({
            fileId: file.fileId,
            fileName: file.fileName
          })
        })
      }
    },
    // 校验
    validate() {
      // 必填项-基本信息
      let requiredOfBase = [
        {
          label: '快检类型',
          key: 'inspectType'
        },
        {
          label: '采样人员',
          key: 'handlerName'
        },
        {
          label: '采样日期',
          key: 'billDate'
        }
      ]
      // 必填项-样品
      let requiredOfSample = [
        {
          label: '样品名称',
          key: 'businessVarietyName'
        },
        {
          label: '采样数量',
          key: 'num'
        }
      ]
      try {
        requiredOfSample.forEach((item) => {
          let value = this.params.details[0][item.key] + ''.trim()
          if (value === '') {
            throw new Error(`${item.label} 为必填项！`)
          }
        })
        requiredOfBase.forEach((item) => {
          let value = this.params[item.key].trim()
          if (value === '') {
            throw new Error(`${item.label} 为必填项！`)
          }
        })
        return true
      } catch (e) {
        this.$toast(e.message)
      }
    },
    toSelect(e) {
      this.active = e
      this.show = true
    },
    // 选择-快检类型
    confirmInspectType() {
      this.params.inspectType = this.$refs.pickerForInspect.getValues()[0]
      this.params.uploadBizType =
        this.params.inspectType === '政府快检' ? 'governmentCheck' : 'ownCheck'
      this.show = false
    },
    // 确定-进货时间
    submitTime() {
      this.params.billDate = ParseDate(this.currentDate)
      this.show = false
    },
    // 提交
    async submit() {
      // 验证各字段是否为空
      if (!this.validate()) return false

      this.params.state = 'ToBeChecked'
      this.params.actionCode = 'ACTION_DATA_CYTZ_CG_TO_DJC'
      this.params.businessFileDTOJson = JSON.stringify(
        this.params.businessFileDTO
      )
      this.params.detailsJson = JSON.stringify(this.params.details)
      // console.log(this.params)
      const { code } = await postSampling(this.params)
      if (code === '0') {
        this.$toast.success('提交成功')
        delKeepaliveCache(this)
        this.$router.go(-1)
      }
    },
    // 保存草稿
    async saveDraft() {
      this.params.state = 'DRAFT'
      this.params.actionCode = 'ACTION_DATA_CYTZ_CG_TO_CG'
      this.params.businessFileDTOJson = JSON.stringify(
        this.params.businessFileDTO
      )
      this.params.detailsJson = JSON.stringify(this.params.details)
      // console.log(this.params)
      const { code } = await postSampling(this.params)
      if (code === '0') {
        this.$toast.success('提交成功')
        delKeepaliveCache(this)
        this.$router.go(-1)
      }
    },
    // 删除-样品信息
    deleteSampleInfo() {
      this.$dialog
        .alert({
          title: '是否删除该信息?',
          showCancelButton: true
        })
        .then(async () => {
          for (let item in this.params.details[0]) {
            if (
              item === 'businessVarietyId' ||
              item === 'businessVarietyName' ||
              item === 'businessVarietyCode' ||
              item === 'num' ||
              item === 'packUnitName'
            ) {
              // 保留样品信息
              continue
            }
            this.params.details[0][item] = ''
          }
          console.log('rrr', this.params.details[0])
        })
        .catch(() => {
          // on cancel
        })
    },
    // 编辑-样品信息
    editSampleInfo(info) {
      info.areaName = this.params.details[0].originPlaceInfoAreaName
      this.$router.push({
        name: 'addSupplyInfo',
        params: {
          info: encodeURIComponent(JSON.stringify(info))
        },
        // 传 intercourseEnterpriseId 和 varietyId， 便于选择进货单号
        query: {
          intercourseEnterpriseId: this.params.intercourseEnterpriseId,
          varietyId: this.varietyId
        }
      })
    }
  }
}
</script>

<style scoped lang="scss"></style>
